﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.Hosting;
using Microsoft.MediaCenter.UI;
using System.IO;
using System.Text;

namespace TV4Home.Client.WMC.TVClient.UI
{
    public class MP : PageBase
    {
        #region Private Fields
        private int currentChannelId = 0;
        private int lastChannelId = 0;
        private TVWebSvc.TVWebService tveCommunicator;
        #endregion

        #region Constructor
        public MP()
        {
            try
            {
                InitTVEWebService();

                PopulateChannelsList();
            }
            catch (Exception ex)
            {
                ShowErrorDialog(ex);
            }
        }
        #endregion

        #region Properties
        private Choice _channels = new Choice();
        public Choice Channels
        {
            get
            {
                return _channels;
            }
            set
            {
                _channels = value;
                this.OnPropertyChanged("Channels");
            }
        }
        #endregion

        #region Public Methods
        public void SomeoneClickedMe(String msg)
        {
            AddInHost.Current.MediaCenterEnvironment.Dialog("Selected: " + msg, "Well Done!", Microsoft.MediaCenter.DialogButtons.Ok, 1000, true);
        }

        public void PauseStream()
        {
            AddInHost.Current.MediaCenterEnvironment.PlayMedia(MediaType.Video, "rtsp://192.168.1.37/stream1.0", false);

            //AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.PlayRate = 1;

        }

        public void FullScreen()
        {
            AddInHost.Current.MediaCenterEnvironment.MediaExperience.GoToFullScreen();
        }

        public void ToggleChannel()
        {
            SwitchToChannel(Convert.ToString(lastChannelId));
        }

        public void SwitchToChannel(string channelIdString)
        {
            try
            {
                int channelId = Convert.ToInt32(channelIdString);

                this.lastChannelId = this.currentChannelId;

                string streamUrl = tveCommunicator.SwitchTVServerToChannelAndGetStreamingUrl(channelId);

                PlayStream(streamUrl);
                GoToEndOfCurrentStream();

                this.currentChannelId = channelId;
            }
            catch (Exception ex)
            {
                ShowErrorDialog(ex);
            }
        }

        public void Disconnect()
        {
            try
            {
                tveCommunicator.Disconnect();
            }
            catch (Exception ex)
            {
                ShowErrorDialog(ex);
            }
        }
        #endregion

        #region Private Methods
        private void InitTVEWebService()
        {
            try
            {
                tveCommunicator = GetTVEWebService(ApplicationSettings.Instance.TVWebServiceURL, ApplicationSettings.Instance.ServerHostName);

                // test connection
                tveCommunicator.Ping();
                tveCommunicator.TestConnectionToTVService();

                // connect
                tveCommunicator.Connect();
            }
            catch (Exception ex)
            {
                ShowErrorDialog(ex);
            }
        }

        internal static TVWebSvc.TVWebService GetTVEWebService(string webSvcUrl, string hostName)
        {
            TVWebSvc.TVWebService webSvc = new TVWebSvc.TVWebService();
            webSvc.Url = String.Format(webSvcUrl, hostName);
            webSvc.CookieContainer = new System.Net.CookieContainer();     // this is required for using sessions in the webservice

            return webSvc;
        }

        private void ShowErrorDialog(Exception ex)
        {
            AddInHost.Current.MediaCenterEnvironment.Dialog(String.Format("An error occurred:\n{0}, StackTrace: {1} ", ex.Message, ex.StackTrace), "Error", DialogButtons.Ok, 0, true);
        }

        private void GoToEndOfCurrentStream()
        {
            AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.Position = TimeSpan.MaxValue; //this.DurationOfCurrentStream;
        }

        private void PlayStream(string streamUrl)
        {
            AddInHost.Current.MediaCenterEnvironment.PlayMedia(MediaType.Video, streamUrl, false);
        }

        private void PopulateChannelsList()
        {
            try
            {
                List<TVWebSvc.WebChannel> tvChannels = new List<TVWebSvc.WebChannel>(tveCommunicator.GetChannels(1));

                if (tvChannels == null || tvChannels.Count == 0)
                    throw new InvalidOperationException("No channels!");

                List<PropertySet> channelsList = new List<PropertySet>();

                foreach (TVWebSvc.WebChannel ch in tvChannels)
                {
                    PropertySet propSet = new PropertySet(this.Owner, "TVChannel");

                    TVWebSvc.WebProgram currentProgram = tveCommunicator.GetCurrentProgramOnChannel(ch.Id);

                    propSet.Entries.Add("ID", ch.Id);
                    propSet.Entries.Add("Name", ch.DisplayName ?? "");
                    propSet.Entries.Add("CurrentProgramTitle", (currentProgram != null) ? currentProgram.Title : "");
                    propSet.Entries.Add("IP-Stream", "rtsp://192.168.1.1/stream7.0");

                    channelsList.Add(propSet);
                }

                _channels.Options = channelsList;
            }
            catch (Exception ex)
            {
                ShowErrorDialog(ex);
            }

        }
        #endregion
    }
}